import { computed } from 'vue'
import { useWebExtensionStorage } from './useWebExtensionStorage'
import type { ExtensionAuthState } from '~/types/auth'

// 使用 WebExtension Storage 持久化认证状态
const { data: authState, dataReady } = useWebExtensionStorage<ExtensionAuthState>('auth_state', {
  isAuthenticated: false,
  user: null,
  token: null,
  lastSync: 0,
  source: 'none',
  status: 'unauthenticated',
  timestamp: Date.now(),
  domain: '',
  expiry: 0,
  loginUrl: '',
}, {
  writeDefaults: false, // 不写入默认值
})

// 添加调试信息
// watch(authState, (newState) => {
//   console.warn('🔍 useAuth authState 变化:', newState)
// }, { deep: true, immediate: true })

// 认证状态管理 composable
export function useAuth() {
  // 计算属性
  const isAuthenticated = computed(() => authState.value.isAuthenticated)
  const currentUser = computed(() => authState.value.user)
  const currentToken = computed(() => authState.value.token)
  const isTokenExpired = computed(() => {
    const { lastSync } = authState.value
    const now = Date.now()
    const maxAge = 24 * 60 * 60 * 1000 // 24小时
    return now - lastSync > maxAge
  })

  // 判断用户登录是否已经失效
  const isLoginExpired = computed(() => {
    const state = authState.value
    const now = Date.now()

    // 如果没有认证或没有token，视为失效
    if (!state.isAuthenticated || !state.token) {
      return true
    }

    // 检查token过期时间（如果有设置expiry）
    if (state.expiry && state.expiry > 0 && now > state.expiry) {
      return true
    }

    // 检查上次同步时间是否超过24小时
    if (state.lastSync && now - state.lastSync > 24 * 60 * 60 * 1000) {
      return true
    }

    return false
  })

  return {
    // 状态
    isAuthenticated,
    currentUser,
    currentToken,
    isTokenExpired,
    isLoginExpired,
    authState: computed(() => authState.value),
    // 数据就绪状态
    dataReady,
  }
}
